﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Qiniu.Storage;
using Qiniu.Util;

namespace TraceabilityApp_Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("请选择要上传的图片");

            // 七牛云配置（请用你自己的替换）
            string accessKey = "k21w5zeHG9FEDlv-r1jUoAWwzc3AQgkBiTJf2FAH";
            string secretKey = "71rk8aV8-hU7A5lzOcR-Y9Listz3m6S4DcNmjqfd";
            string bucket = "qwerimgs";
            string domain = "szfg2lukp.hb-bkt.clouddn.com";

            // 生成上传凭证
            Mac mac = new Mac(accessKey, secretKey);
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = bucket;
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 读取文件流
            var stream = file.OpenReadStream();
            var key = $"images/{System.Guid.NewGuid()}{Path.GetExtension(file.FileName)}";

            // 创建Config对象
            Config config = new Config();
            // 上传
            FormUploader fu = new FormUploader(config);
            var result = await Task.Run(() => fu.UploadStream(stream, key, token, null));

            if (result.Code == 200)
            {
                string url = $"{domain}/{key}";
                return Ok(new { url });
            }
            else
            {
                return StatusCode(500, result.Text);
            }
        }
    }
}
